package com.dongan.controller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongan.pojo.Codes;
import com.dongan.pojo.Users;
import com.dongan.pojo.UsersRoleMenu;
import com.dongan.service.CodesService;
import com.dongan.service.UsersService;
import com.dongan.utils.CommonProp;
import com.dongan.utils.JwtUtils;
import com.dongan.utils.ResultResponseUtil;
import com.dongan.utils.SerialNumber;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author longTao
 * @since 2021-06-15
 */
@RestController
@RequestMapping(value = "/api/ucenter/wx")
@CrossOrigin
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private CodesService codesService;
    /**
     * 用户登录
     * @param users
     * @return
     */
    @RequestMapping(value = "/loginUserNameAndPassword",method = RequestMethod.POST)
    public ResultResponseUtil loginUserNameAndPassword(@RequestBody Users users){
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("ID","LOGIN_ID","PHOTO_PATH");
        queryWrapper.eq("email",users.getEmail());
        queryWrapper.eq("PASSWORD",users.getPassword());
        Users one = usersService.getOne(queryWrapper);
        CommonProp.user=one;
        System.out.println("one = " + one);
        if (null==one){
            return new ResultResponseUtil(false,"用户名或密码错误,请重新登录!");
        }
        SerialNumber.user=one;
        dataInit();
        return new ResultResponseUtil(true,"登录成功!",one);
    }

    public void dataInit(){
        List<Codes> codesList=codesService.list();
        for (Codes codes : codesList) {
            if("fileSN".equals(codes.getName())){
                SerialNumber.fileSN=Integer.valueOf(codes.getDefValue());
            }
            if("moduleSN".equals(codes.getName())){
                SerialNumber.moduleSN=Integer.valueOf(codes.getDefValue());
            }
            if("designProcedureSN".equals(codes.getName())){
                SerialNumber.designProcedureSN=Integer.valueOf(codes.getDefValue());
            }
        }
    }


    /**
     * 用户新建
     * @param map
     * @return
     */
    @CrossOrigin
    @PostMapping(value = "/")
    @PreAuthorize("hasAuthority('/userCreation')")
    public ResultResponseUtil userAdd(@RequestBody Map<String,Object> map){
        ObjectMapper mapper=new ObjectMapper();
        String message = null;
        Users users =null;
        try {
            message = mapper.readValue(map.get("message").toString(), String.class);
            String s = mapper.writeValueAsString(map.get("users"));
            users =mapper.readValue(s, Users.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
//        System.out.println("message = " + message);
//        System.out.println("users = " + users);
//        System.out.println("CommonProp.verificationCode = " + CommonProp.verificationCode);
        if (!CommonProp.verificationCode.equals(message)){
            return new ResultResponseUtil(false,"验证码不正确");
        }
        boolean save = usersService.save(users);
        if (save){
            return new ResultResponseUtil(save,"用户新建成功!");
        }else {
            return new ResultResponseUtil(save,"用户新建失败!");
        }
    }

    /**
     * 用户普通查询
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/userQuery")
    @PreAuthorize("hasAuthority('/userQuery')")
    public ResultResponseUtil userQuery(String name,String pageNum,String pageSize){
        QueryWrapper<Users> usersQueryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)){
            usersQueryWrapper.like("LOGIN_ID",name);
        }
        if (StringUtils.isEmpty(pageNum)){
            pageNum="1";
        }
        if (StringUtils.isEmpty(pageSize)){
            pageSize="2";
        }
        Page<Users> page=new Page<>();
        page.setSize(Long.valueOf(pageSize));
        page.setCurrent(Long.valueOf(pageNum));
        Page<Users> usersPage = usersService.page(page, usersQueryWrapper);
        return new ResultResponseUtil(true,usersPage);
    }


    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('/userQuery')")
    @GetMapping(value = "/userQueryById/{id}",produces = {"application/json;charset=UTF-8"})
    public ResultResponseUtil userQueryById(@PathVariable Long id){
        Users users = usersService.getById(id);
        return new ResultResponseUtil(true,users);
    }


    /**
     * 根据id修改用户
     * @param users
     * @return
     */
    @PreAuthorize("hasAuthority('/userModification')")
    @PutMapping(value = "/",produces = {"application/json;charset=utf-8"})
    public ResultResponseUtil userUpdateById(@RequestBody Users users){
        boolean flag = usersService.updateById(users);
        if (flag){
            return new ResultResponseUtil(true,"修改成功!");
        }else {
            return new ResultResponseUtil(false,"修改失败!");
        }
    }

    /**
     * 根据id查询用户详情
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('/userQuery')")
    @GetMapping(value = "/{id}",produces = {"application/json;charset=utf-8"})
    public ResultResponseUtil userQueryDetailsById(@PathVariable Long id){
        UsersRoleMenu usersRoleMenu = usersService.queryById(id);
        return new ResultResponseUtil(true,usersRoleMenu);
    }

    /**
     * 发送验证码
     * @param account
     * @return
     */

    @CrossOrigin
    @GetMapping(value = "/email/{account}",produces = {"application/json;charset=utf-8"})
    public ResultResponseUtil sendVerificationCodeAccordingToAccount(@PathVariable String account){
      usersService.sendTheVerificationCode(account);
        return new ResultResponseUtil(true,"邮件发送成功!");
    }

    /**
     * 根据id进行逻辑删除用户和之间的角色关系
     * @param id
     * @return
     */
    @PreAuthorize("hasAuthority('/userDelete')")
    @CrossOrigin
    @DeleteMapping(value = "/{id}",produces = {"application/json;charset=utf-8"})
    public ResultResponseUtil deleteUserBasedOnId(@PathVariable Long id){
        boolean flag = usersService.deleteUserById(id);
        return flag==true?new ResultResponseUtil(true,"用户删除成功!"):new ResultResponseUtil(false,"用户删除失败!");
    }


    /**
     * 登录
     * @param users
     * @return
     */
    @PostMapping(value = "/login",produces = "application/json;charset=utf-8")
        public ResultResponseUtil loginUser(@RequestBody Users users){
        //调用service方法实现登录
        //返回token值,使用jwt生成
        String token=usersService.login(users);
        if (StringUtils.isEmpty(token)){
            return new ResultResponseUtil(false,"用户名或密码错误!",token);
        }else {
            QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
            queryWrapper.select("ID","LOGIN_ID","PHOTO_PATH");
            queryWrapper.eq("email",users.getEmail());
            queryWrapper.eq("PASSWORD",users.getPassword());
            Users one = usersService.getOne(queryWrapper);
            System.out.println("one = " + one);
            CommonProp.user=one;
            SerialNumber.user=one;
            System.out.println("SerialNumber.user = " + SerialNumber.user);
            dataInit();
            return new ResultResponseUtil(true,"登录成功!",token);
        }
    }

    @GetMapping(value = "/getMemberInfo")
    public ResultResponseUtil getMemberInfo(HttpServletRequest request){
        //调用jwt工具类的方法,根据request对象获取头信息,返回用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        Users users = usersService.getById(Long.valueOf(id));
        return new ResultResponseUtil(true,users);
    }
}

